//
//  WBTestViewController.m
//  Fozua
//
//  Created by MingmingSun on 2016/11/28.
//  Copyright © 2016年 Sunmingming. All rights reserved.
//

#import "WBTestViewController.h"
#import "JBCountdownLabel.h"
#import "StockKeyboard.h"
#import "WubiWordItem.h"
#import "WubiPhraseItem.h"
#import "WubiZigenItem.h"
#import "WBTestItem.h"
#import <Colours.h>
#import <Masonry.h>

#import "tooles.h"
#import "AppDelegate.h"

@interface WBTestViewController ()<CountdownDelegate,WubiKBDelegate>

@property(nonatomic,strong) UIImageView *bgImageview;
@property(nonatomic,strong) UILabel *headLabel;
@property(nonatomic,strong) UILabel *titleLabel;
@property(nonatomic,strong) UILabel *questionLabel;
@property(nonatomic,strong) UIImageView *questionImageview;
@property(nonatomic,strong) JBCountdownLabel *timeLabel;
@property(nonatomic,strong) UILabel *scoreLabel;
@property(nonatomic,strong) UILabel *answerLabel;
@property(nonatomic,strong) UILabel *resultLabel;

@property(nonatomic,strong) StockKeyboard *keyboard;

@property(nonatomic,strong) NSMutableString *inputStr;
@property(nonatomic,assign) int nowScore;
@property(nonatomic,assign) int sumTimes;
@property(nonatomic,assign) int correctTimes;
@property(nonatomic,strong) WubiPhraseItem *answerPhraseItem;
@property(nonatomic,strong) WubiWordItem *answerWordItem;
@property(nonatomic,strong) WubiZigenItem *answerZigenItem;
@property(nonatomic,strong) WBTestItem *answerTestItem;

@property(nonatomic,strong) NSString *answerStr;
@property(nonatomic,assign) Boolean waiting;

@end

@implementation WBTestViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	if (self) {
		self.navigationItem.leftBarButtonItem =
		[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrow_white"]
																		 style:UIBarButtonItemStyleDone
																		target:self
																		action:@selector(backPressed:)];
		
		self.answerPhraseItem = nil;
		self.answerWordItem = nil;
		self.answerZigenItem = nil;
		self.answerTestItem = nil;
		self.answerStr = @"";
		self.waiting = NO;
		
		self.bgImageview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"aboutus1136"]];
		self.bgImageview.contentMode = UIViewContentModeScaleToFill;
		[self.view addSubview:self.bgImageview];
		
		self.headLabel = [UILabel new];
		self.headLabel.textAlignment = NSTextAlignmentCenter;
		self.headLabel.font = [UIFont systemFontOfSize:15.0f];
		self.headLabel.text = @"head";
		[self.view addSubview:self.headLabel];
		
		self.titleLabel = [UILabel new];
		self.titleLabel.textAlignment = NSTextAlignmentCenter;
		self.titleLabel.font = [UIFont boldSystemFontOfSize:18.0f];
		self.titleLabel.text = @"title";
		[self.view addSubview:self.titleLabel];
		
		self.questionLabel = [UILabel new];
		self.questionLabel.textAlignment = NSTextAlignmentCenter;
		self.questionLabel.font = [UIFont boldSystemFontOfSize:40.0f];
		self.questionLabel.backgroundColor = [UIColor beigeColor];
		self.questionLabel.text = @"";
		[self.view addSubview:self.questionLabel];
		
		self.questionImageview = [UIImageView new];
		self.questionImageview.backgroundColor = [UIColor whiteColor];
		self.questionImageview.contentMode = UIViewContentModeScaleAspectFit;
		[self.view addSubview:self.questionImageview];
		
		self.timeLabel = [[JBCountdownLabel alloc] initWithFrame:CGRectMake(0, 50,kViewWidth,20) format:@"%@秒" time:10 delegate:self];
		self.timeLabel.textAlignment = NSTextAlignmentCenter;
		self.timeLabel.font = [UIFont systemFontOfSize:15.0f];
		[self.view addSubview:self.timeLabel];
		
		self.scoreLabel = [UILabel new];
		self.scoreLabel.textAlignment = NSTextAlignmentCenter;
		self.scoreLabel.font = [UIFont systemFontOfSize:15.0f];
		self.scoreLabel.textColor = [UIColor redColor];
		self.scoreLabel.text = @"score";
		[self.view addSubview:self.scoreLabel];
		
		self.answerLabel = [UILabel new];
		self.answerLabel.textAlignment = NSTextAlignmentCenter;
		self.answerLabel.backgroundColor = [UIColor beigeColor];
		self.answerLabel.font = [UIFont boldSystemFontOfSize:18.0f];
		self.answerLabel.text = @"answer";
		[self.view addSubview:self.answerLabel];
		
		self.resultLabel = [UILabel new];
		self.resultLabel.textAlignment = NSTextAlignmentCenter;
		self.resultLabel.numberOfLines = 0;
		self.resultLabel.font = [UIFont boldSystemFontOfSize:14.0f];
		self.resultLabel.text = @"result";
		[self.view addSubview:self.resultLabel];
		
		self.keyboard = [[StockKeyboard alloc] initWithLabel:self.answerLabel];
		self.keyboard.delegate = self;
		[self.view addSubview:self.keyboard];
	}
	return self;
}

-(void)backPressed:(id)sender
{
	[self.timeLabel cancelCountdown];
	[self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
	[super viewWillAppear:animated];
	self.headLabel.text = @"100分过关，对一题加2分，错1题减2分。";
	switch (self.myTag) {
		case ETestZigen:
			self.title = @"字根练习";
			self.titleLabel.text = @"请输入下图中红色标识字根的键位：";
			break;
		case ETestZi:
			self.title = @"单字练习";
			self.titleLabel.text = @"请输入下方单字的四字编码：";
			break;
		case ETestCiyu:
			self.title = @"词语练习";
			self.titleLabel.text = @"请输入下方词语的四字编码：";
			break;
		case ETestTimeless:
			self.title = @"自由单字练习";
			self.titleLabel.text = @"请输入下方单字的四字编码：";
			self.headLabel.text = @"自由练习没有时间限制，对一题加2分。";
			break;
		default:
			break;
	}
	int heightspace = 8;
	WS(ws);
	[self.bgImageview mas_makeConstraints:^(MASConstraintMaker *make) {
		make.edges.equalTo(ws.view);
	}];
	
	[self.headLabel mas_makeConstraints:^(MASConstraintMaker *make) {
		make.size.mas_equalTo(CGSizeMake(kViewWidth,20));
		make.top.mas_equalTo(ws.view.mas_top).with.offset(ws.navigationController.navigationBar.frame.size.height + 40 + 10);
		make.centerX.mas_equalTo(ws.view.mas_centerX);
	}];
	
	[self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
		make.size.mas_equalTo(CGSizeMake(kViewWidth,20));
		make.top.mas_equalTo(self.headLabel.mas_bottom).with.offset(heightspace);
		make.centerX.mas_equalTo(ws.view.mas_centerX);
	}];
	
	[self.questionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
		make.size.mas_equalTo(CGSizeMake(kViewWidth/2,60));
		make.top.mas_equalTo(self.titleLabel.mas_bottom).with.offset(heightspace);
		make.centerX.mas_equalTo(ws.view.mas_centerX);
	}];
	
	[self.questionImageview mas_makeConstraints:^(MASConstraintMaker *make) {
		make.size.mas_equalTo(CGSizeMake(60,60));
		make.centerX.mas_equalTo(self.questionLabel.mas_centerX);
		make.centerY.mas_equalTo(self.questionLabel.mas_centerY);
	}];
	
	[self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
		make.size.mas_equalTo(CGSizeMake(kViewWidth,20));
		make.top.mas_equalTo(self.questionLabel.mas_bottom).with.offset(heightspace);
		make.centerX.mas_equalTo(ws.view.mas_centerX);
	}];
	
	[self.scoreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
		make.size.mas_equalTo(CGSizeMake(kViewWidth,20));
		make.top.mas_equalTo(self.timeLabel.mas_bottom).with.offset(heightspace);
		make.centerX.mas_equalTo(ws.view.mas_centerX);
	}];
	[self.resultLabel mas_makeConstraints:^(MASConstraintMaker *make) {
		make.size.mas_equalTo(CGSizeMake(kViewWidth,40));
		make.top.mas_equalTo(self.scoreLabel.mas_bottom).with.offset(heightspace);
		make.centerX.mas_equalTo(ws.view.mas_centerX);
	}];
	
	[self.keyboard mas_makeConstraints:^(MASConstraintMaker *make) {
		make.size.mas_equalTo(CGSizeMake(kViewWidth,216));
		make.bottom.mas_equalTo(ws.view.mas_bottom).with.offset(-APPALL.window.safeAreaInsets.bottom);
		make.centerX.mas_equalTo(ws.view.mas_centerX);
	}];
	
	[self.answerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
		make.size.mas_equalTo(CGSizeMake(kViewWidth,35));
		make.bottom.mas_equalTo(self.keyboard.mas_top);
		make.centerX.mas_equalTo(ws.view.mas_centerX);
	}];
	
	self.nowScore = 0;
	self.sumTimes = 0;
	self.correctTimes = 0;
	self.answerPhraseItem = nil;
	self.questionLabel.text = @"";
	self.scoreLabel.text = @"练习马上开始！";
	self.resultLabel.text = @"";
	self.inputStr = [NSMutableString stringWithString:@""];
	self.answerLabel.text = self.inputStr;
	switch (self.myTag) {
		case ETestZigen:
			self.questionLabel.hidden = YES;
			self.questionImageview.hidden = NO;
			self.timeLabel.hidden = NO;
			[self.timeLabel setTime:5];
			[self.timeLabel restartCountdown];
			break;
		case ETestTimeless:
			self.questionImageview.hidden = YES;
			self.questionLabel.hidden = NO;
			self.timeLabel.hidden = YES;
			[self.timeLabel cancelCountdown];
			[self nextQuestion];
			break;
		default:
			self.questionImageview.hidden = YES;
			self.questionLabel.hidden = NO;
			self.timeLabel.hidden = NO;
			[self.timeLabel setTime:5];
			[self.timeLabel restartCountdown];
			break;
	}
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

-(void)wbKeyPressed:(NSString*)aStr
{
	NSLog(@"hahaha :%@",aStr);
	if(aStr.length > 1) {
		if (self.waiting) {
			[self nextQuestion];
		}
		return;
	}
	if(!self.answerStr.length)//first time
		return;
	if([aStr isEqualToString:@"←"]){
		if(self.myTag == ETestZigen)
			return;
		if(self.inputStr.length > 0){
			[self.inputStr setString:[self.inputStr substringToIndex:self.inputStr.length - 1]];
			self.answerLabel.text = self.inputStr;
		}
		if([self.answerStr hasPrefix:self.inputStr]){
			self.answerLabel.textColor = [UIColor blackColor];
		}
		else{
			self.answerLabel.textColor = [UIColor redColor];
		}
		return;
	}
	if([aStr isEqualToString:@"→"]){
		if(self.myTag == ETestZigen)
			return;
		if(self.inputStr.length > 0)
		{
			[self.inputStr setString:@""];
			self.answerLabel.textColor = [UIColor blackColor];
			self.answerLabel.text = self.inputStr;
		}
		return;
	}
	if(self.inputStr.length >= self.answerStr.length)
	{
		[self.inputStr setString:@""];
	}
	[self.inputStr appendString:aStr];
	self.answerLabel.text = self.inputStr;
	if([self.answerStr hasPrefix:self.inputStr]){
		self.answerLabel.textColor = [UIColor blackColor];
	}
	else{
		self.answerLabel.textColor = [UIColor redColor];
	}
	if(self.inputStr.length < self.answerStr.length)
		return;
	NSString* cacheQ = @"";
	if(self.myTag == ETestZigen){
		cacheQ = [tooles wubiSentenceByChara:self.answerStr];
	}else{
		cacheQ = self.questionLabel.text;
	}
	if([self.answerStr isEqualToString:self.inputStr])
	{
		//correct
		self.nowScore += 2;
		self.correctTimes ++;
		self.resultLabel.text = [NSString stringWithFormat:@"正确！%@(%@)\n按空格继续下一练习！",cacheQ,self.answerStr];
		self.resultLabel.textColor = [UIColor blackColor];
	}
	else
	{
		//wrong
		self.nowScore = self.nowScore > 2?self.nowScore - 2 : 0;
		self.resultLabel.text = [NSString stringWithFormat:@"错误,%@(%@)\n按空格继续下一练习！",cacheQ,self.answerStr];
		self.resultLabel.textColor = [UIColor redColor];
	}
	if(self.nowScore < 100)
	{
		[self.timeLabel cancelCountdown];
		self.waiting = YES;
		return;
	}
	[self.timeLabel cancelCountdown];
	if([APPALL.mydefaults integerForKey:@"nowLevel"] <= 8)
	{
		[APPALL.mydefaults setInteger:9 forKey:@"nowLevel"];
		UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"恭喜您成功过关！" message:nil preferredStyle:UIAlertControllerStyleAlert];
		//    vc.view.backgroundColor = [UIColor goldColor];
		UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
			[self.navigationController popViewControllerAnimated:YES];
		}];
		[vc addAction:cancelAction];
		[self presentViewController:vc animated:NO completion:nil];
	}
}

- (void)countdownFinnishIn:(JBCountdownLabel *)countdown{
	if(!self.answerStr.length)//first time
	{
		self.correctTimes = 0;
		self.sumTimes = -1;
	}
	else
	{
		if(self.myTag == ETestZigen){
			self.resultLabel.text = [NSString stringWithFormat:@"正确答案:%@(%@)\n按空格继续下一练习！",self.answerStr,[tooles wubiSentenceByChara:self.answerStr]];
		}else{
			self.resultLabel.text = [NSString stringWithFormat:@"正确答案:%@\n按空格继续下一练习！",self.answerStr];
		}
		self.resultLabel.textColor = [UIColor redColor];
		[self.timeLabel cancelCountdown];
		self.waiting = YES;
		self.nowScore = self.nowScore > 2?self.nowScore-2 : 0;
		return;
	}
	self.nowScore = self.nowScore > 2?self.nowScore-2 : 0;
	[self nextQuestion];
}

-(void)nextQuestion
{
	self.waiting = NO;
	self.resultLabel.text = @"";
	self.sumTimes++;
	switch (self.myTag) {
		case ETestZigen:{
			int randomOne = arc4random() % 223 + 1;
			self.answerZigenItem = [WubiZigenItem searchSingleWithWhere:[NSString stringWithFormat:@"wbid = %d",randomOne] orderBy:nil];
			NSLog(@"%@",self.answerZigenItem.value);
			self.questionImageview.image = [UIImage imageNamed:self.answerZigenItem.value];
			self.answerStr = [self.answerZigenItem.value substringToIndex:1];
			[self.timeLabel setTime:5];
		}
			break;
		case ETestZi:{
			int randomOne = arc4random() % 1000 + 1;
			self.answerWordItem = [WubiWordItem searchSingleWithWhere:[NSString stringWithFormat:@"wbid = %d",randomOne] orderBy:nil];
			//do nothing.
			NSLog(@"%@__%@",self.answerWordItem.value,self.answerWordItem.wbvalue);
			self.questionLabel.text = self.answerWordItem.value;
			self.answerStr = self.answerWordItem.wbvalue;
			[self.timeLabel setTime:20];
		}
			break;
		case ETestCiyu:{
			int randomOne = arc4random() % 1000 + 1;
			self.answerPhraseItem = [WubiPhraseItem searchSingleWithWhere:[NSString stringWithFormat:@"wbid = %d",randomOne] orderBy:nil];
			//do nothing.
			NSLog(@"%@__%@",self.answerPhraseItem.value,self.answerPhraseItem.wbvalue);
			self.questionLabel.text = self.answerPhraseItem.value;
			self.answerStr = self.answerPhraseItem.wbvalue;
			[self.timeLabel setTime:20];
		}
			break;
		case ETestTimeless:{
			int randomOne = arc4random() % 1000 + 1;
			self.answerWordItem = [WubiWordItem searchSingleWithWhere:[NSString stringWithFormat:@"wbid = %d",randomOne] orderBy:nil];
			//do nothing.
			NSLog(@"%@__%@",self.answerWordItem.value,self.answerWordItem.wbvalue);
			self.questionLabel.text = self.answerWordItem.value;
			self.answerStr = self.answerWordItem.wbvalue;
		}
			break;
		case ETestAll:{
			[self.timeLabel setTime:20];
		}
			break;
		default:
			break;
	}
	[self.inputStr setString:@""];
	int correctRate = 0;
	if(self.sumTimes > 0)
		correctRate = (self.correctTimes * 100)/self.sumTimes;
	self.scoreLabel.text = [NSString stringWithFormat:@"正确率:%d%% ,%d分",correctRate,self.nowScore];
	if(self.myTag != ETestTimeless){
		[self.timeLabel restartCountdown];
	}
}

-(void)dealloc
{
	[self.timeLabel cancelCountdown];
}

@end
